package fun.codedesign.principle.advice151.a129;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockCondition {

    /**
     * condition的使用方式
     * newCondition返回一个相应的对象
     * 该对象依赖于锁Lock
     * 当condition.await 时，其他将可以通过Lock.lock() 获得锁，如果不是用这种方式将无法获得锁
     * 可以用多个condition进行不同条件的处理，也可以用一个条件进行在两个线程中进行 await和signal操作，
     * 但此时需要保证有一条线程先走，可以用Thread.sleep() 在加锁前进行处理
     *
     * @param args
     */
    public static void main(String[] args) {

        final Lock lock = new ReentrantLock();
        final Condition c1 = lock.newCondition();
        // final Condition c2 = lock.newCondition();
        final AtomicInteger a1 = new AtomicInteger(1);

        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                Increament(a1);
                try {
                    c1.signal();
                    c1.await();  // 释放lock锁
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Increament(a1);
                try {
                    c1.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                lock.unlock();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                Increament(a1);
                try {
                    c1.signal();
                    c1.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Increament(a1);
                lock.unlock();
            }
        }).start();
    }

    private static void Increament(AtomicInteger a1) {
        for (int j = 0; j < 3; j++) {
            System.out.println(Thread.currentThread().getName() + ":" + a1.getAndIncrement());
        }
    }
}
